<script setup lang="ts">
import router from '@/router'
import {
  getPatientList,
  addPatient,
  editPatient,
  deletePatient
} from '@/services/user'
import { useStore } from '@/stores'
import type { Patient, PatientList } from '@/types/user'
import { nameRules, idCardRules } from '@/utils/validate'
import { showConfirmDialog, type FormInstance, showSuccessToast } from 'vant'
import { computed } from 'vue'
import { watch, ref } from 'vue'
import { useRoute } from 'vue-router'
const { consult } = useStore()
const list = ref<PatientList>([])
// 获取患者列表
const getList = async () => {
  const res = await getPatientList()
  list.value = res.data
  // 保证患者列表有长度后再调用默认选中
  defaultSelect()
}
getList()

const isShow = ref(false)

const options = [
  { label: '男', value: 1 },
  { label: '女', value: 0 }
]
// 新增患者的数据
const formData = ref<Patient>({
  name: '',
  idCard: '',
  defaultFlag: 0,
  gender: 1
})
// defaultFlag为了覆写formData.defaultFlag
const defaultFlag = ref<0 | 1>(0)
watch(
  () => formData.value.defaultFlag,
  (newVal) => {
    defaultFlag.value = newVal ? 1 : 0
  }
)
const formRef = ref<null | FormInstance>(null)
// 保存提交
const save = async () => {
  // console.log({ ...formData.value, defaultFlag: defaultFlag.value })
  // 1. 校验
  await formRef.value?.validate()
  // 2. 性别和身份证冲突 身份证号倒数第二位 偶数 是 女性 奇数 男性
  // 2.1 取到倒数第二位
  const num = +formData.value.idCard.slice(-2, -1) // 4
  // 2.2 和2取余
  // num % 2 === 0  / 1 ?
  // 2.3 和选中的formData.gender比较
  if (num % 2 !== formData.value.gender) {
    // console.log('性别选中有问题')
    await showConfirmDialog({
      title: '温馨提示',
      message: '填写的性别和身份证号不一致\n您确认提交么?'
    })
  }

  if (formData.value.id) {
    // 删除掉多余的字段
    delete formData.value.genderValue
    delete formData.value.age
    // 发送编辑提交
    await editPatient({ ...formData.value, defaultFlag: defaultFlag.value })
  } else {
    //  3. 发送新增请求
    await addPatient({ ...formData.value, defaultFlag: defaultFlag.value })
  }
  // 4. 提示
  showSuccessToast('新增成功')
  // 5. 关闭侧滑弹层
  isShow.value = false
  // 6. 重新获取
  getList()
}
//  关闭侧滑弹层重置
watch(
  () => isShow.value,
  (newVal) => {
    if (!newVal) {
      // 1. 清除错误提示
      formRef.value?.resetValidation()
      // 2. 将表单还原
      formData.value = {
        name: '',
        idCard: '',
        defaultFlag: 0,
        gender: 1
      }
    }
  }
)
// 编辑回显
const showEdit = (patient: Patient) => {
  // 1. 展示弹层
  isShow.value = true
  // 2. 回显
  formData.value = patient
}

// 删除
const del = async (id: string) => {
  // 1. 确认提示
  await showConfirmDialog({
    title: '温馨提示',
    message: '您确认移除该患者么?'
  })
  // 2. 发送请求
  await deletePatient(id)
  // 3. 移除侧滑
  isShow.value = false
  // 4. 重新获取
  getList()
}

const route = useRoute()
const isChange = computed(() => route.query.isChange)
// 患者的点击切换高亮
const patientId = ref('')
const selectPatientId = (id: string) => {
  if (id && isChange.value) {
    patientId.value = id
  }
}

// 默认选中
const defaultSelect = () => {
  if (isChange.value && list.value.length) {
    const o = list.value.find((item) => item.defaultFlag)
    if (o) {
      patientId.value = o.id as string
    } else {
      patientId.value = list.value[0].id as string
    }
  }
}

// 记录患者id
const next = () => {
  if (patientId.value) {
    consult.setPatientId(patientId.value)
    router.push('/consult/pay')
  }
}
</script>
<template>
  <div class="patient-page">
    <cp-nav-bar title="家庭档案"></cp-nav-bar>
    <div class="patient-change" v-if="isChange">
      <h3>请选择患者信息</h3>
      <p>以便医生给出更准确的治疗，信息仅医生可见</p>
    </div>

    <div class="patient-list">
      <div
        class="patient-item"
        :class="{ selected: patientId === item.id }"
        v-for="item in list"
        :key="item.id"
        @click="selectPatientId(item.id as string)"
      >
        <div class="info">
          <span class="name">{{ item.name }}</span>
          <!-- 脱敏  身份证号脱敏 手机号脱敏-->
          <span class="id">{{
            item.idCard.replace(/(\w{6})\w*(\w{4})/, '$1********$2')
          }}</span>
          <span>{{ item.genderValue }}</span>
          <span>{{ item.age }}岁</span>
        </div>
        <div class="icon">
          <cp-icon name="user-edit" @click="showEdit(item)" />
        </div>
        <div class="tag" v-if="item.defaultFlag">默认</div>
      </div>
      <div class="patient-add" v-if="list.length < 6" @click="isShow = true">
        <cp-icon name="user-add" />
        <p>添加患者</p>
      </div>
      <div class="patient-tip">最多可添加 6 人</div>
    </div>
    <!-- 底部按钮 -->
    <div class="patient-next" v-if="isChange">
      <van-button type="primary" round block @click="next">下一步</van-button>
    </div>
    <!-- 新增患者展示侧滑弹出层 -->
    <van-popup
      v-model:show="isShow"
      position="right"
      style="width: 100%; height: 100%"
    >
      <cp-nav-bar
        :title="formData.id ? '编辑患者' : '添加患者'"
        right-text="保存"
        :back-fn="() => (isShow = false)"
        @click-right="save"
      ></cp-nav-bar>
      <van-form autocomplete="off" ref="formRef">
        <van-field
          label="真实姓名"
          placeholder="请输入真实姓名"
          v-model="formData.name"
          :rules="nameRules"
        />
        <van-field
          label="身份证号"
          placeholder="请输入身份证号"
          v-model="formData.idCard"
          :rules="idCardRules"
        />
        <van-field label="性别" class="pb4">
          <!-- 单选按钮组件 -->
          <template #input>
            <cp-radio-btn
              :options="options"
              v-model="formData.gender"
            ></cp-radio-btn>
          </template>
        </van-field>
        <van-field label="默认就诊人">
          <template #input>
            <van-checkbox
              :icon-size="18"
              round
              v-model="formData.defaultFlag"
            />
          </template>
        </van-field>
      </van-form>

      <!-- 1. 按需显示 准备删除按钮
           2. 为删除按钮绑定点击 传递id
           3. 确认提示
           4. 准备接口发送请求
      -->
      <van-action-bar v-if="formData.id">
        <van-action-bar-button text="删除" @click="del(formData.id)" />
      </van-action-bar>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.patient-change {
  padding: 15px;
  > h3 {
    font-weight: normal;
    margin-bottom: 5px;
  }
  > p {
    color: var(--cp-text3);
  }
}
.patient-next {
  padding: 15px;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 80px;
  box-sizing: border-box;
}

.patient-page {
  padding: 46px 0 80px;
  :deep() {
    .van-popup {
      width: 100%;
      height: 100%;
      padding-top: 46px;
      box-sizing: border-box;
    }
  }
}

.patient-list {
  padding: 15px;
}
.patient-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: var(--cp-bg);
  border-radius: 8px;
  margin-bottom: 15px;
  position: relative;
  border: 1px solid var(--cp-bg);
  transition: all 0.3s;
  overflow: hidden;
  .info {
    display: flex;
    flex-wrap: wrap;
    flex: 1;
    span {
      color: var(--cp-tip);
      margin-right: 20px;
      line-height: 30px;
      &.name {
        font-size: 16px;
        color: var(--cp-text1);
        width: 80px;
        margin-right: 0;
      }
      &.id {
        color: var(--cp-text2);
        width: 180px;
      }
    }
  }
  .icon {
    color: var(--cp-tag);
    width: 20px;
    text-align: center;
  }
  .tag {
    position: absolute;
    right: 60px;
    top: 21px;
    width: 30px;
    height: 16px;
    font-size: 10px;
    color: #fff;
    background-color: var(--cp-primary);
    border-radius: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  &.selected {
    border-color: var(--cp-primary);
    background-color: var(--cp-plain);
    .icon {
      color: var(--cp-primary);
    }
  }
}
.patient-add {
  background-color: var(--cp-bg);
  color: var(--cp-primary);
  text-align: center;
  padding: 15px 0;
  border-radius: 8px;
  .cp-icon {
    font-size: 24px;
  }
}
.patient-tip {
  color: var(--cp-tag);
  padding: 12px 0;
}
.pb4 {
  padding-bottom: 4px;
}
// 底部操作栏
.van-action-bar {
  padding: 0 10px;
  margin-bottom: 10px;
  .van-button {
    color: var(--cp-price);
    background-color: var(--cp-bg);
  }
}
</style>
